import React, { useEffect, useState } from "react";
import NavBar from "@/components/NavBar/NavBar";
import SearchBar from "@/components/SearchBar/SearchBar";
import SvgIcon from "@/components/SvgIcon/SvgIcon";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Good, SearchParams } from "@/type/SearchType";
import { searchGoodListThunk } from "@/store/modules/searchStore";
import { DotLoading, Empty, Tabs, Toast } from "antd-mobile";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import GoodCard from "@/components/GoodCard/GoodCard";
import GoodItem from "@/components/GoodItem/GoodItem";
import "./GoodList.scss";

const GoodList = () => {
   const navigate = useNavigate();

   const enhanceDispatch = useEnhanceDispatch();

   const goodList: Good[] = useEnhanceSelector(state => state.searchStore.goodList);

   const [searchParams] = useSearchParams();

   // 商品名称
   const goodsName: string = searchParams.get("goodsName") as string;
   // 商品分类ID
   const categoryId: string = searchParams.get("categoryId") as string;
   // 查询商品的参数
   const [params, setParams] = useState<SearchParams>({
      page: 1,
      goodsName: goodsName,
      categoryId: categoryId,
      sortType: "all",
      sortPrice: undefined,
   });
   // SvgIcon图标名名称
   const [iconName, setIconName] = useState<string>("card");
   // 当前激活项
   const [activeKey, setActiveKey] = useState<"all" | "sales" | "price">("all");

   const [loading, setLoading] = useState<boolean>(false);

   /**
    * @description 获取商品列表的回调函数
    * */
   const searchGood = async () => {
      try {
         setLoading(true);
         await enhanceDispatch(searchGoodListThunk(params)).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      } finally {
         setLoading(false);
      }
   };

   /**
    * @description 切换svgicon图标的回调函数
    * */
   const changeSvgIcon = () => {
      setIconName(iconName === "item" ? "card" : "item");
   };

   /**
    * @description 切换选中项的回调函数
    * */
   const changeActiveKey = (activeKey: string) => {
      setActiveKey(activeKey as "all" | "sales" | "price");
      setParams({ ...params, sortType: activeKey });
   };

   const renderGoodList = () => {
      if (iconName === "item") {
         return (
            <div className="good-item-list">
               {
                  loading ? <div className="lazy-loading"><DotLoading color="primary"></DotLoading></div> : goodList.map((item, index) => (<GoodItem good={item} key={item.goods_id}></GoodItem>))
               }
            </div>
         );
      } else if (iconName === "card") {
         return (
            <div className="good-card-list">
               {

                  loading ? <div className="lazy-loading"><DotLoading color="primary"></DotLoading></div> : goodList.map((item, index) => (<GoodCard good={item} key={item.goods_id}></GoodCard>))
               }
            </div>
         );
      }
   };

   useEffect(() => {
      searchGood();
   }, [params]);

   return (
      <div className="good-list-container">
        <div className="good-list-header">
           <NavBar children="商品列表" backIcon onBack={() => navigate(-1)}></NavBar>
           <SearchBar placeholder={goodsName || "搜索商品"}>
              <span onClick={changeSvgIcon}><SvgIcon name={iconName} width="20px" height="20px"></SvgIcon></span>
           </SearchBar>
           <Tabs activeKey={activeKey} onChange={changeActiveKey}>
              <Tabs.Tab title="综合" key="all"></Tabs.Tab>
              <Tabs.Tab title="销量" key="sales"></Tabs.Tab>
              <Tabs.Tab title="价格" key="price"></Tabs.Tab>
           </Tabs>
        </div>
         {
            renderGoodList()
         }
         {
            goodList.length === 0 && <Empty description="暂无数据"></Empty>
         }
      </div>
   );
};

export default GoodList;
